package com.gds.wiki.cloud.admin.server.modular.sys.service;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gds.wiki.cloud.admin.client.sys.model.Resource;
import com.gds.wiki.cloud.admin.client.sys.model.Role;
import com.gds.wiki.cloud.admin.client.sys.model.SysRoleResource;
import com.gds.wiki.cloud.admin.client.sys.model.query.RoleQuery;
import com.gds.wiki.cloud.admin.server.modular.sys.mapper.ResourceMapper;
import com.gds.wiki.cloud.admin.server.modular.sys.mapper.RoleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class RoleService extends ServiceImpl<RoleMapper, Role> {

     @Autowired
     private RoleMapper roleMapper;

     @Autowired
     private SysRoleResourceService sysRoleResourceService;

     @Autowired
     private ResourceMapper resourceMapper;

    public List<Map> findUserRoleByUid(Long uid) {
          return roleMapper.getRoleByUid(uid);
    }


    @Transactional
    public Boolean AuthRoleResource(Long rid,String[]ids) {

        roleMapper.DelRoleResourceBy(rid);
        List<SysRoleResource> list=new ArrayList<>();
        for(String id:ids){
            SysRoleResource sysRoleResource=new SysRoleResource();
            sysRoleResource.setRoleId(rid);
            sysRoleResource.setResourceId(Long.valueOf(id));
            list.add(sysRoleResource);
        }
       boolean rs= sysRoleResourceService.saveBatch(list);
        if(!rs){
            return false;
        }
        return true;
    }

        public List<Map> roleSelect(Long deptId) {
        return roleMapper.getRoleByDeptId(deptId);
    }


        public List<Map> roleResources(Long rid) {
        List<Resource> list=  resourceMapper.getResourceByRoleId(rid);
        return treeList(list,0l);
    }


        public List<Map> treeList(List<Resource> list,Long parentId){
        List mapList = new ArrayList();
        for (Resource resource : list) {
            if (resource.getPid()==parentId) {
                Map map=new HashMap();
                map.put("id",resource.getId());
                map.put("name",resource.getName());
                List<Map> c_node = treeList(list, resource.getId());
                map.put("child", c_node);
                mapList.add(map);
            }
        }
        return mapList;
    };

    public Page selectPage(RoleQuery roleQuery){
        return roleMapper.getRoleWithDept(new Page<>(roleQuery.getPage(), roleQuery.getSize()),roleQuery);
    };
}
